package com.framework2.util;

import android.app.Activity;
import android.content.Context;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.WindowManager;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.asiainfo.iov.activity.LoginActivity;
import com.asiainfo.iov.configs.ConstantsME;
import com.asiainfo.iov.configs.EventBusTag;
import com.asiainfo.iov.configs.InterfaceConfig;
import com.asiainfo.iov.networkModel.HttpUtil;
import com.framework.security.RSAmethodInAssets;
import com.framework.utils.KeyBoardUtil;
import com.framework.utils.PreferencesHelper;
import com.framework.utils.ToastUtil;
import com.framework.utils.Y;
import com.framework2.popupwindow.BindingPhonePopupwindow;
import com.tencent.connect.UserInfo;
import com.tencent.connect.common.Constants;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.yaxin.yyt.R;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

/**
 * 三方授权登录util
 *
 * @author YobertJomi
 * className ThirdLoginUtil
 * created at  2017/4/25  13:59
 */
public class ThirdQQLoginUtil {
    private static volatile ThirdQQLoginUtil singleton;
    //*************************************************************************************QQ_Login
    private Tencent mTencent;
    private UserInfo qqUserInfo;
    private String mAppid = "1106106460";
    private Context context;
    private String qqOpenId;
    private String qqImgUrl;
    private String qqNick;
    private String phoneTemp;
    private String pwdTemp;
    private String captchaTemp;
    private int thirdType = 2;//2qq  3wchat
    private MyCountDownTimer myCountDownTimer;
    private String verifyKey;//验证码key
    //*************************************************************************************QQ_Login
    public IUiListener loginListener = new BaseUiListener() {
        @Override
        protected void doComplete(JSONObject values) {
            initOpenidAndToken(values);
            CustomLoadingDialogUtils.showProcessDialog(context, "关联手机号");
            qqUserInfo = new UserInfo(context, mTencent.getQQToken());
            qqUserInfo.getUserInfo(new BaseUiListener() {
                @Override
                protected void doComplete(JSONObject values) {
                    super.doComplete(values);
                    if (null == values) {
                        CustomLoadingDialogUtils.dismissProcessDialog();
                        return;
                    }
                    Y.y("json=" + String.valueOf(values));
                    String nickName = values.optString("nickname");
                    qqNick = nickName;
                    qqImgUrl = values.optString("figureurl_qq_2");
//                    requestThirdLoginBindPhone(0, RSAmethod.rsaDecrypt(context, PreferencesHelper.getInstance()
// .getStringData(ConstantsME.PHONE)),
//                            qqOpenId, qqImgUrl, qqNick);
//                    showBindingPop(context, thirdType, RSAmethod.rsaEncrypt(context, PreferencesHelper.getInstance
// ().getStringData(ConstantsME.PHONE)), qqOpenId, pwdTemp, captchaTemp);
                    requestThirdLoginCheckBinding(context, thirdType, qqOpenId, qqImgUrl, qqNick);
                }
            });
        }
    };

    private ThirdQQLoginUtil() {
    }

    public static ThirdQQLoginUtil getInstance() {
        if (singleton == null) {
            synchronized (ThirdQQLoginUtil.class) {
                if (singleton == null) {
                    singleton = new ThirdQQLoginUtil();
                }
            }
        }
        return singleton;
    }

    public void qqLogin(Context context) {
        if (!TextUtils.isEmpty(qqOpenId) && !TextUtils.isEmpty(qqImgUrl) && !TextUtils.isEmpty(qqNick)) {
            CustomLoadingDialogUtils.showProcessDialog(context, "关联手机号");
//            requestThirdLoginBindPhone(0, RSAmethod.rsaDecrypt(context, PreferencesHelper.getInstance()
// .getStringData(ConstantsME.PHONE)),
//                    qqOpenId, qqImgUrl, qqNick);
            requestThirdLoginCheckBinding(context, thirdType, qqOpenId, qqImgUrl, qqNick);
//            showBindingPop(context, thirdType, RSAmethod.rsaEncrypt(context, PreferencesHelper.getInstance()
// .getStringData(ConstantsME.PHONE)), qqOpenId, pwdTemp, captchaTemp);
        } else {
            CustomLoadingDialogUtils.showProcessDialog(context, "跳转到QQ");
            this.context = context;
            if (mTencent == null) {
                mTencent = Tencent.createInstance(mAppid, context);
            }
            if (mTencent != null) {
//        if (!mTencent.isSessionValid()) {
                mTencent.login((LoginActivity) context, "all", loginListener);//TODO Yobert-LoginActivity
//        }
            }
        }
    }

    private void initOpenidAndToken(JSONObject jsonObject) {
        try {
            Y.y("initOpenidAndToken：" + jsonObject.toString());
            String token = jsonObject.getString(Constants.PARAM_ACCESS_TOKEN);
            String expires = jsonObject.getString(Constants.PARAM_EXPIRES_IN);
            String openId = jsonObject.getString(Constants.PARAM_OPEN_ID);
            if (!TextUtils.isEmpty(token) && !TextUtils.isEmpty(expires)
                    && !TextUtils.isEmpty(openId)) {
                qqOpenId = openId;
                mTencent.setAccessToken(token, expires);
                mTencent.setOpenId(openId);
            }
        } catch (Exception e) {
        }
    }

    /**
     * 请求 检测三方登录是否绑定phone
     */
    private void requestThirdLoginCheckBinding(final Context context, final int type, final String openId, final
    String imgUrl, final String nick) {
        HttpUtil.getInstance().requestThirdLoginCheckBinding(InterfaceConfig.thirdLoginCheckBinding, type, openId,
                nick, imgUrl,
                new HttpUtil.OnRequestResult<String>() {
                    @Override
                    public void onSuccess(String... s) {
                        CustomLoadingDialogUtils.dismissProcessDialog();
                        if (null != s) {
                            if (!TextUtils.isEmpty(s[0])) {
                                PreferencesHelper.getInstance().putInfo(ConstantsME.PHONE, RSAmethodInAssets.rsaEncrypt
                                        (context, s[0]));
                            }
//                            PreferencesHelper.getInstance().putInfo(ConstantsME.token, s.length > 1 ? s[1] : "");
//                            PreferencesHelper.getInstance().putInfo(ConstantsME.nick, s.length > 2 ? s[2] : "");
//                            PreferencesHelper.getInstance().putInfo(ConstantsME.imgUrl, s.length > 3 ? s[3] : "");
                            PreferencesHelper.getInstance().putInfo(ConstantsME.LOGINED, true);
                            showBindingPop(context, thirdType, RSAmethodInAssets.rsaDecrypt(context, PreferencesHelper
                                    .getInstance().getStringData(ConstantsME.PHONE)), qqOpenId, pwdTemp, captchaTemp);
                        } else {
                            showBindingPop(context, thirdType, RSAmethodInAssets.rsaDecrypt(context, PreferencesHelper
                                    .getInstance().getStringData(ConstantsME.PHONE)), qqOpenId, pwdTemp, captchaTemp);
                        }
                    }

                    @Override
                    public void onFail(int code, String msg) {
                        CustomLoadingDialogUtils.dismissProcessDialog();
                        ToastUtil.getInstance().showToast(TextUtils.isEmpty(msg) ? "未检测是否绑定手机" : msg);
//                        showBindingPop(context,type, "", openId, "", "");
                        showBindingPop(context, thirdType, RSAmethodInAssets.rsaDecrypt(context, PreferencesHelper
                                .getInstance().getStringData(ConstantsME.PHONE)), qqOpenId, pwdTemp, captchaTemp);
                    }
                });
    }

    /**
     * 请求 三方登录绑定phone
     */
    private void requestThirdLoginBindPhone(final int type, final String openId, final String phone, final String
            mobileValidVoucher, final String moblieVerifyCode, final String password) {
        HttpUtil.getInstance().requestThirdLoginBindPhone(InterfaceConfig.thirdLoginBindPhone, type, openId, phone,
                mobileValidVoucher, moblieVerifyCode, password,
                new HttpUtil.OnRequestResult<String>() {
                    @Override
                    public void onSuccess(String... s) {
                        CustomLoadingDialogUtils.dismissProcessDialog();
                        if (null != s) {
                            if (!TextUtils.isEmpty(s[0]) && TextUtils.equals("true", s[0])) {
                                PreferencesHelper.getInstance().putInfo(ConstantsME.PHONE, RSAmethodInAssets.rsaEncrypt
                                        (context, phone));

                                if (s.length > 1 && !TextUtils.isEmpty(s[1]))
                                    PreferencesHelper.getInstance().putInfo(ConstantsME.token, s[1]);
                                if (s.length > 2 && !TextUtils.isEmpty(s[2]))
                                    PreferencesHelper.getInstance().putInfo(ConstantsME.nick, s[2]);
                                if (s.length > 3 && !TextUtils.isEmpty(s[3]))
                                    PreferencesHelper.getInstance().putInfo(ConstantsME.imgUrl, s[3]);
                                PreferencesHelper.getInstance().putInfo(ConstantsME.LOGINED, true);
                                if (type == 2) {
                                    PreferencesHelper.getInstance().putInfo(ConstantsME.qqBind, true);
                                    EventBus.getDefault().post("success", EventBusTag.thirdBindingQQ);
                                } else if (type == 3) {
                                    PreferencesHelper.getInstance().putInfo(ConstantsME.wChatBind, true);
                                    EventBus.getDefault().post("success", EventBusTag.thirdBinding);
                                }
                            } else {
                                onFail(1, "");
                            }
                        }
                    }

                    @Override
                    public void onFail(int code, String msg) {
                        ToastUtil.getInstance().showToast(TextUtils.isEmpty(msg) ? "绑定失败" : msg);
                        CustomLoadingDialogUtils.dismissProcessDialog();
                        showBindingPop(context, type, phone, openId, password, moblieVerifyCode);
                    }
                });
    }

    private void showBindingPop(final Context context, final int type, String phone, final String openId, final
    String pwd, final String captcha) {
        CustomLoadingDialogUtils.dismissProcessDialog();
        ((Activity) context).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED |
                WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        final BindingPhonePopupwindow pop = new BindingPhonePopupwindow(context);
        long last = PreferencesHelper.getInstance().getLongData(ConstantsME.captcha_last_clicked);
        long currentTimeMillis = System.currentTimeMillis();
        long difference = currentTimeMillis - last;
        int diff = (int) ((60 * 1000 - difference) / 1000);
        if (difference < 60 * 1000 && diff >= 1) {
            new MyCountDownTimer(context, pop.getCaptcaTextView(), diff * 1000, 1000).start();
        }
        pop.setContent(phone).setPassword(pwd).setCaptcha(captcha).setOnGetCaptchaListener(new BindingPhonePopupwindow.OnGetCaptchaListener() {
            @Override
            public void onGetCaptchaListener(String phoneNum) {
                myCountDownTimer = new MyCountDownTimer(context, pop.getCaptcaTextView(), 60000, 1000);
                myCountDownTimer.start();
                PreferencesHelper.getInstance().putInfo(ConstantsME.captcha_last_clicked, System.currentTimeMillis());
                CustomLoadingDialogUtils.showProcessDialog(context, "获取验证码");
                requestCaptcha(context, pop.getCaptcaTextView(), phoneNum);
            }
        });
        pop.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                ((Activity) context).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN |
                        WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
            }
        });
        pop.setOnSureClickListener(new BindingPhonePopupwindow.OnSureClickListener() {
            @Override
            public void onSureClickListener(String phone, String pwd, String captcha) {
                phoneTemp = phone;
                pwdTemp = pwd;
                captchaTemp = captcha;
                if (TextUtils.isEmpty(verifyKey)) {
                    ToastUtil.getInstance().showToast("请先获取验证码");
                } else {
                    CustomLoadingDialogUtils.showProcessDialog(context, "正在绑定QQ号");
                    KeyBoardUtil.getInstance().isCloseSoftInputMethod(context, pop.getEditText(), true);
                    requestThirdLoginBindPhone(type, openId, phone, verifyKey, captcha, pwd);
                    pop.dismiss();
                }
            }
        }).showAtLocation(((Activity) context).getWindow().getDecorView(), Gravity.CENTER, 0, 0);
    }

    /**
     * 请求获取验证码
     */
    private void requestCaptcha(final Context context, final TextView tv_captcha, String phone) {
        HttpUtil.getInstance().requestMobileVerify(InterfaceConfig.captcha, 4, phone,
                new HttpUtil.OnRequestResult<String>() {
                    @Override
                    public void onSuccess(String... s) {
                        CustomLoadingDialogUtils.dismissProcessDialog();
                        ToastUtil.getInstance().showToast("获取验证码成功");
                        if (null != s && !TextUtils.isEmpty(s[0])) {
                            verifyKey = s[0];
                        }
                    }

                    @Override
                    public void onFail(int code, String msg) {
                        CustomLoadingDialogUtils.dismissProcessDialog();
                        ToastUtil.getInstance().showToast(TextUtils.isEmpty(msg) ? "获取验证码失败" : msg);
                        PreferencesHelper.getInstance().putInfo(ConstantsME.captcha_last_clicked, 0L);
                        if (null != myCountDownTimer)
                            myCountDownTimer.cancel();
                        tv_captcha.setText("重新获取");
                        tv_captcha.setTextColor(context.getResources().getColor(R.color._blue));
                        tv_captcha.setClickable(true);
                    }
                });
    }

    public void destroy() {
        if (singleton != null) {
            singleton = null;
        }
        if (context != null) {
            context = null;
        }
        if (mTencent != null) {
            mTencent = null;
        }
        if (myCountDownTimer != null) {
            myCountDownTimer.cancel();
            myCountDownTimer = null;
        }
    }

    private class BaseUiListener implements IUiListener {

        @Override
        public void onComplete(Object response) {
            Y.y("qq===onComplete.....");
            if (null == response) {
                ToastUtil.getInstance().showToast("返回为空" + "登录失败");
                return;
            }
            JSONObject jsonResponse = (JSONObject) response;
            if (null != jsonResponse && jsonResponse.length() == 0) {
                ToastUtil.getInstance().showToast("返回为空" + "登录失败");
                return;
            }
            doComplete((JSONObject) response);
        }

        protected void doComplete(JSONObject values) {

        }

        @Override
        public void onError(UiError e) {
            CustomLoadingDialogUtils.dismissProcessDialog();
            ToastUtil.getInstance().showToast("QQ授权错误: " + e.errorDetail);
        }

        @Override
        public void onCancel() {
            CustomLoadingDialogUtils.dismissProcessDialog();
            ToastUtil.getInstance().showToast("已取消QQ授权");
        }
    }

    private class MyCountDownTimer extends CountDownTimer {
        private TextView tv_captcha;

        public MyCountDownTimer(Context context, TextView tv_captcha, long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);// 参数依次为总时长,和计时的时间间隔
            this.tv_captcha = tv_captcha;
        }

        @Override
        public void onFinish() {// 计时完毕时触发
            tv_captcha.setText("重新获取");
            tv_captcha.setTextColor(context.getResources().getColor(R.color._blue));
            tv_captcha.setClickable(true);
        }

        @Override
        public void onTick(long millisUntilFinished) {// 计时过程显示
            try {
                tv_captcha.setClickable(false);
                tv_captcha.setTextColor(context.getResources().getColor(
                        R.color.trans));
                tv_captcha.setText(millisUntilFinished / 1000 + "秒");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
